<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>11_上传图片验证</title>
</head>
<body>
    <label for="file">上传图片格式验证:</label>
    <input type="file" name="" id="file">
    <script type="text/javascript">
        // jpg png gif  jpeg
        window.onload = function() {
            // 1.获取标签
            var file = document.getElementById('file');
            // 2.监听图片选择的变化
            file.onchange = function(){
                // 2.1 获取上传的图片路径
                var path = this.value;
                console.log(path);
                // 2.2 获取.在路径字符串中占的位置
                var loc = path.lastIndexOf('.');
                console.log(loc);
                // 2.3 截图 文件路径的后缀名
                var suffix = path.substr(loc);
                // 2.4 统一转小写
                var lower_suffix = suffix.toLowerCase();
                // 2.5 判断
                if(lower_suffix === '.jpg' || lower_suffix === '.png' || lower_suffix === '.jpeg' || lower_suffix === '.gif'){
                    alert('上传图片格式正确');
                }else{
                    alert('上传图片格式错误');
                }
            }
        }
    </script>
</body>
</html>